package com.umeox.watch.moto.launcher.ui.widget;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.AssetManager;
import android.graphics.Typeface;
import android.text.format.DateFormat;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.umeox.moto.common.log.Logger;
import com.umeox.watch.moto.dataservice.DataProvider;
import com.umeox.watch.moto.launcher.R;
import com.umeox.watch.moto.launcher.event.WatchFaceChangeEvent;
import com.umeox.watch.moto.pedometer.util.CacheImpl;
import com.umeox.watch.moto.pedometer.util.ICache;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;

public class NumberClockView extends RelativeLayout {

    private static final int BATTERY_FULL = 100;
    private final Typeface mTfPollerOneRegular;
    private Typeface mTfPostnobillscolomboExtrabold;
    private TextView mDateTv;
    private TextView mTimeTv;
    private TextView mHourTv;
    private TextView mMinTv;
    private Context mContext;
    private TextView mAmPmTv;

    private ImageView mForegroundIv;

    public NumberClockView(Context context) {
        this(context, null);
    }

    public NumberClockView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public NumberClockView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mContext = context;

        AssetManager mgr = context.getAssets();
        mTfPollerOneRegular = Typeface.createFromAsset(mgr, "font/PollerOne-Regular.ttf");
        mTfPostnobillscolomboExtrabold = Typeface.createFromAsset(mgr, "font/postnobillscolombo-extrabold.ttf");
        initView();
    }

    private void initView() {
        int wallpaper = DataProvider.getWallpaper();
        int resId = R.layout.view_clock;
        if (wallpaper == 8) {
            resId = R.layout.view_number_clock8;
        }
        final View view = LayoutInflater.from(mContext).inflate(resId, this);
        mTimeTv = view.findViewById(R.id.tv_time);
        mAmPmTv = view.findViewById(R.id.tv_am_pm);
        mDateTv = view.findViewById(R.id.tv_date);
        mHourTv = view.findViewById(R.id.tv_time_hour);
        mMinTv = view.findViewById(R.id.tv_time_min);
        mForegroundIv = view.findViewById(R.id.iv_foreground);
        updateDateTime();

        initTextStyle(wallpaper);
    }


    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        EventBus.getDefault().register(this);
        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_TIME_TICK);
        filter.addAction(Intent.ACTION_TIME_CHANGED);
        filter.addAction(Intent.ACTION_TIMEZONE_CHANGED);
        filter.addAction(Intent.ACTION_LOCALE_CHANGED);
        mContext.registerReceiver(mBroadcastReceiver, filter, null, null);
        updateDateTime();
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onWatchFaceChangeEvent(WatchFaceChangeEvent event) {
        final int position = event.mPosition;
        initTextStyle(position);

    }

    private void initTextStyle(int position) {
        if (position == 0 || position == 4 || position == 7) {
            mTimeTv.setTypeface(mTfPollerOneRegular);
            mAmPmTv.setTypeface(mTfPollerOneRegular);
            if (position == 0){
                boolean showPrayTime = CacheImpl.getInstance().get(ICache.KEY_WATCH_FACE_ICON_INDEX, 0) == 0;
                if(!showPrayTime){
                    View timCl = findViewById(R.id.time_cl);
                    FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) timCl.getLayoutParams();
                    layoutParams.setMargins(0,50,0,0);
                    timCl.setLayoutParams(layoutParams);
                }
            }
        } else if (position == 1) {
            mTimeTv.setTypeface(mTfPostnobillscolomboExtrabold);
            mAmPmTv.setTypeface(mTfPostnobillscolomboExtrabold);
            boolean showForeground = CacheImpl.getInstance().get(ICache.KEY_WATCH_FACE_ICON_INDEX, 0) == 0;
            mForegroundIv.setVisibility(showForeground ? View.VISIBLE : View.INVISIBLE);

            boolean showPrayTime = CacheImpl.getInstance().get(ICache.KEY_WATCH_FACE_ICON_INDEX, 0) == 0;
            if(!showPrayTime){
                View timCl = findViewById(R.id.time_cl);
                FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) timCl.getLayoutParams();
                layoutParams.setMargins(0,60,0,0);
                timCl.setLayoutParams(layoutParams);
            }

        } else if (position == 3) {
            boolean showPrayTime = CacheImpl.getInstance().get(ICache.KEY_WATCH_FACE_ICON_INDEX, 0) == 0;
            if(!showPrayTime){
                View timCl = findViewById(R.id.time_cl);
                FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) timCl.getLayoutParams();
                layoutParams.setMargins(0,102,0,0);
                timCl.setLayoutParams(layoutParams);
            }
        }

        int[] timeColors = getResources().getIntArray(R.array.time_color);
        int[] dateColors = getResources().getIntArray(R.array.date_color);
        if (mTimeTv != null) {
            mTimeTv.setTextColor(timeColors[position]);
        }

        mAmPmTv.setTextColor(timeColors[position]);
        mDateTv.setTextColor(dateColors[position]);

        int[] timeTextSize = getResources().getIntArray(R.array.time_text_size);
        int[] amPmTextSize = getResources().getIntArray(R.array.am_pm_text_size);

        if (mTimeTv != null) {
            mTimeTv.setTextSize(TypedValue.COMPLEX_UNIT_PX, timeTextSize[position]);
        }
        if (mHourTv != null) {
            mHourTv.setTextSize(TypedValue.COMPLEX_UNIT_PX, timeTextSize[position]);
        }
        if (mMinTv != null) {
            mMinTv.setTextSize(TypedValue.COMPLEX_UNIT_PX, timeTextSize[position]);
        }
        mAmPmTv.setTextSize(TypedValue.COMPLEX_UNIT_PX, amPmTextSize[position]);
    }


    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        EventBus.getDefault().unregister(this);
        mContext.unregisterReceiver(mBroadcastReceiver);
    }


    private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Logger.e("NumberClockView", "action:" + intent.getAction());
            updateDateTime();
        }
    };


    /**
     * 更新日期\时间
     */
    private void updateDateTime() {
        final SimpleDateFormat DATE_FORMAT_24 = new SimpleDateFormat("EEE MM/dd-H:mm-a", Locale.getDefault());
        final SimpleDateFormat DATE_FORMAT_12 = new SimpleDateFormat("EEE MM/dd-h:mm-a", Locale.getDefault());
        final boolean hourFormat_24 = DateFormat.is24HourFormat(mContext);
        SimpleDateFormat dateFormat = hourFormat_24 ? DATE_FORMAT_24 : DATE_FORMAT_12;
        final Calendar now = Calendar.getInstance();
        final String format = dateFormat.format(now.getTimeInMillis());

        Logger.e("NumberClockView", "currentTime:" + format);
        final String[] dates = format.split("-");

        mDateTv.setText(dates[0]);

        if (mTimeTv != null) {
            mTimeTv.setText(dates[1]);
        }

        if (mHourTv != null) {
            mHourTv.setText(String.format(Locale.getDefault(), "%02d", Integer.parseInt(dates[1].split(":")[0])));
            mMinTv.setText(dates[1].split(":")[1]);
        }
        if (!hourFormat_24) {
            mAmPmTv.setVisibility(View.VISIBLE);
            mAmPmTv.setText(dates[2]);
        } else {
            mAmPmTv.setVisibility(View.INVISIBLE);
        }
    }
}
